#include <interrupt.h>
#include <io.h>
#include <SoftwareSerial.h>

#include "DataContainer.h"
#include "typedef.h"
#include "WeatherDataGenerator.h"
#include "RS232Trace.h"

#define INTERRUPT_CMP_CNT 149

int int_counter = 0, counter = 0;
long currentTimer = 0, timerDiff = 0, lastTimer = 0;
long currentTimer2 = 0, timerDiff2 = 0, lastTimer2 = 0;


DataContainer* ringBuffer = DataContainer::GetInstance();

/********************************************************/
/*				Interrupt routine						*/
/********************************************************/
ISR(TIMER2_COMPA_vect) 
{
	cli();

	int_counter++;

	SignalBit bit;

	/* read bit operation */
	bit = ringBuffer->getBit();

	// set pin and led to bit value
	if(bit == 0xFF)
	{
		digitalWrite(13, 0x00);
	}
	else
	{
		digitalWrite(13, bit);
	}

	sei();
}

/********************************************************/
/*					setup routine						*/
/********************************************************/
void setup()
{
	//delay(2000);
	pinMode(13, OUTPUT);	// LED for signaling current send bit

	pinMode(4, INPUT);	// CLS

	// cli();             // disable global interrupts

	// Aruino runs at 16 Mhz, so we need to have to get an interrupt after 1.2 ms
	TCCR2A = 0;		// clear timer settings register
	TCCR2B = 0;		// clear timer settings register

	// set compare match register to calculated timer count:

	// 155 => 1,248 ms
	// 149 => 1,200 ms
	// 125 => 1,000 ms

	//OCR2A = 59;
	//OCR2A = 149;
	OCR2A = INTERRUPT_CMP_CNT;

	// turn on CTC mode:
	TCCR2A |= (1 << WGM21);

	// Set CS20 and CS22 bits for 128 prescaler:
	// 155 => 1,248 ms
	// 149 => 1,200 ms
	// 125 => 1,000 ms
	TCCR2B |= (1 << CS20);
	TCCR2B |= (1 << CS22);
	// TCCR2B |= (1 << CS22);

	// Set CS20 - CS22 bits for 1024 prescaler:
	// OCR2A = 155 => 9.984 ms
	/*TCCR2B |= (1 << CS20);
	TCCR2B |= (1 << CS21);
	TCCR2B |= (1 << CS22);*/

	// enable timer compare interrupt:
	// TIMSK2 |= (1 << OCIE2A);

	// enable global interrupts:
	// sei();
}

/********************************************************/
/*					main routine						*/
/********************************************************/
int speed = 0;
void loop()
{
	if(digitalRead(4) == LOW)
	{
		TIMSK2 |= (1 << OCIE2A);

		int currentBufferSize;

		// Create new instance of data generator
		WeatherDataGenerator gen(ringBuffer);

		// generate weather data
		DataSet newDataSet = gen.CreateWeatherData(speed, speed++);

		// write data to buffer
		gen.WriteWeatherData(newDataSet);

		// wait 2 sec
		delay(500);
	}
	else
	{
		TIMSK2 &= ~(1 << OCIE2A);
	}




}